// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FileRequestHelper.cs" company="XamlNinja">
//   2011 Richard Griffin and Ollie Riches
// </copyright>
// <summary>
//   FileRequestHelper.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace WP7Contrib.Services.DownloadManager
{
    using System.IO;
    using System.IO.IsolatedStorage;

    /// <summary>
    /// Provides helper methods for file download requests - such as file name, directory etc...
    /// </summary>
    internal static class FileRequestHelper
    {
        public static void WriteToFile(PersistedFileRequest request, byte[] data)
        {
            var directory = ExtractDirectory(request.FilePath);
            using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!isoFile.DirectoryExists(directory))
                {
                    isoFile.CreateDirectory(directory);

                }
                using (var stream = isoFile.OpenFile(request.FilePath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    stream.Seek(0, SeekOrigin.End);
                    stream.Write(data, 0, data.Length);

                    stream.Flush();
                }
            }
        }

        public static bool DoesFileExist(PersistedFileRequest request)
        {
            return DoesFileExistImpl(request.FilePath);
        }

        public static void DeleteFile(PersistedFileRequest request)
        {
            if (!DoesFileExistImpl(request.FilePath))
            {
                return;
            }

            using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                isoFile.DeleteFile(request.FilePath);
            }
        }

        public static long GetFileLength(PersistedFileRequest request)
        {
            using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isoFile.FileExists(request.FilePath))
                {
                    using (var stream = isoFile.OpenFile(request.FilePath, FileMode.Open))
                    {
                        return stream.Length;
                    }
                }
            }

            return 0;
        }

        private static string ExtractDirectory(string path)
        {
            var lastIndex = path.LastIndexOf('\\');
            return lastIndex == -1 ? null : path.Substring(0, lastIndex);
        }

        private static bool DoesFileExistImpl(string path)
        {
            using (var iosFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                return iosFile.FileExists(path);
            }
        }
    }
}